import { loginApi, getUserProfileApi, getUserInfoById } from '@/api/user'
import { setToken as setTokenToCookie, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setTokenToCookie(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  logOut(state) {
    state.token = ''
    removeToken()
    state.userInfo = {}
  }
}
const actions = {
  // login(store, data) {
  //   // 使用Promise封装的目的： 让组件内部拿到接口响应结果之后 才进行跳转
  //   return new Promise((resolve, reject) => {
  //     loginApi(data).then((res) => {
  //       store.commit('setToken', res.data)
  //       resolve(res)
  //     }).catch(err => {
  //       reject(err)
  //     })
  //   })
  // },
  async login(store, data) {
    // 使用Promise封装的目的： 让组件内部拿到接口响应结果之后 才进行跳转
    const res = await loginApi(data)
    store.commit('setToken', res.data)
    return res
  },
  async getUserInfo(store) {
    const res = await getUserProfileApi()
    const res2 = await getUserInfoById(res.data.userId)
    const baseResult = {
      ...res.data,
      ...res2.data
    }
    store.commit('setUserInfo', baseResult)
    return baseResult
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
